package com.ming.sportdemo.controller;

import com.alibaba.fastjson.JSON;
import com.ming.sportdemo.config.ServerConfig;
import com.ming.sportdemo.config.WebAppConfigurer;
import com.ming.sportdemo.config.WebConfig;
import com.ming.sportdemo.service.FieldService;
import org.aspectj.weaver.patterns.HasMemberTypePattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UploadController {

    public static String baseURL=null;

    @Autowired
    FieldService fieldService;

    @Autowired
    private ServerConfig serverConfig;

    @Value("${file.upload.path.relative}")
    private String fileRelativePath;


    @Value("${file.upload.path}")
    private String filePath; //D:\\fileupload

    //指定文件的上传路径，这里是静态资源下的images
    public static String dirPath = System.getProperty("user.dir");//定位到工程根目录
    public static String imgPath = dirPath+"\\src\\main\\resources\\static\\images";


    @PostMapping(value = "/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request){

        System.out.println("文件上传:"+multipartFile.getOriginalFilename());
        String filename = multipartFile.getOriginalFilename();//获得文件名以及后缀名
        System.out.println(dirPath);
        File filepath = new File(imgPath);
        //判断文档目录是否存在，不存在的话则创建
        if(!filepath.exists()){
            filepath.mkdir();
        }
        try{
            multipartFile.transferTo(new File(imgPath+File.separator+filename));//将文件写入磁盘
            //数据操作
            String name = "/images/"+filename;
            baseURL =  name;
            System.out.println("存入数据库:"+name);
            Map<String,Object> res = new HashMap<>();
            res.put("filename",name);
            System.out.println("访问图片地址:"+name);
            return JSON.toJSONString(res);


        }catch (IOException e){
            e.printStackTrace();
            return null;
        }
    }
}
